﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DOA_Tentamen_20150115_Betyg5
{
    public class HashTable<TKey, TValue>
    {
        private Node<TKey, TValue>[] array;
        private Node<TKey, TValue> head = new Node<TKey, TValue>();
        

        public HashTable(int size)
        {
            array = new Node<TKey, TValue>[size];
               
            for (int i = 0; i < size; i++)
            {
                Node<TKey, TValue> n = new Node<TKey, TValue>();
                n.Next = head.Next;
                head.Next = n;
                array[i] = n;
            }           
        }

        public void Add(TKey key, TValue value)
        {
            int hash = Math.Abs(key.GetHashCode() % array.GetLength(0));
            Node<TKey, TValue> n = new Node<TKey, TValue>(key, value);

            Node<TKey, TValue> temp = new Node<TKey, TValue>();
            temp = head;
            for (int i = 0; i < hash - 1 ; i++) //Hamnar på den innan
            {
                temp = temp.Next;
            }
            n.Next = temp.Next;
            temp.Next = n;
            array[hash] = n;

        }

        public Node<TKey, TValue> Search(TKey key)
        {
            int hash = Math.Abs(key.GetHashCode() % array.GetLength(0));
            Node<TKey, TValue> n = array[hash];
            while (n.Key != null && !n.Key.Equals(key))
            {
                n = n.Next;
            }
            return n;
        }

        public void Print()
        {
            Node<TKey, TValue> temp = new Node<TKey, TValue>();
            temp = head;

            while(temp.Next != null)
            {
                if(temp == head)
                {
                    Console.WriteLine("Head");
                    temp = temp.Next;
                }

                else if(temp.Key == null)
                {
                    temp = temp.Next;
                }

                else
                {
                    Console.WriteLine(temp.Key + " : " + temp.Value);
                    temp = temp.Next;
                }
            }

        }

    }
}
